<template>
  <div class="dashboard-container">
    <!-- 用户数据模块 -->
    <t-card title="用户数据" class="dashboard-card">
      <!-- 用户增长曲线图 -->
      <div class="chart-container">
        <div class="chart-header">
          <h3>用户增长趋势</h3>
          <t-radio-group v-model="userGrowthTimeRange" variant="default-filled" size="small">
            <t-radio-button value="30">最近30天</t-radio-button>
            <t-radio-button value="180">最近半年</t-radio-button>
            <t-radio-button value="365">最近一年</t-radio-button>
          </t-radio-group>
        </div>
        <div class="chart-wrapper">
          <div ref="userGrowthChartRef" class="chart"></div>
          <div v-if="loading" class="chart-loading-overlay">
            <t-loading size="medium" />
          </div>
        </div>
        <div class="chart-footer">
          <div class="chart-legend">
            <span class="legend-item">
              <span class="legend-color" style="background-color: #0052d9;"></span>
              <span class="legend-text">用户总数</span>
            </span>
          </div>
          <div class="chart-info">
            <t-tooltip content="数据每日更新，展示用户总数随时间的变化趋势">
              <t-icon name="help-circle" />
            </t-tooltip>
          </div>
        </div>
      </div>

      <!-- 用户数据卡片 -->
      <div class="data-cards">
        <div class="data-card">
          <div class="data-card-content">
            <div class="data-card-title">用户总数</div>
            <div class="data-card-value">{{ formatNumber(totalUsers) }}</div>
            <div class="data-card-trend" :class="{ 'up': userGrowthRate > 0, 'down': userGrowthRate < 0 }">
              <t-icon :name="userGrowthRate >= 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(userGrowthRate) }}%</span>
              <span class="trend-label">较上月</span>
            </div>
          </div>
          <div class="data-card-icon" style="background: linear-gradient(135deg, #0052d9 0%, #1890ff 100%);">
            <t-icon name="usergroup" />
          </div>
        </div>

        <div class="data-card">
          <div class="data-card-content">
            <div class="data-card-title">本月活跃用户</div>
            <div class="data-card-value">{{ formatNumber(monthlyActiveUsers) }}</div>
            <div class="data-card-trend" :class="{ 'up': monthlyActiveRate > 0, 'down': monthlyActiveRate < 0 }">
              <t-icon :name="monthlyActiveRate >= 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(monthlyActiveRate) }}%</span>
              <span class="trend-label">较上月</span>
            </div>
          </div>
          <div class="data-card-icon" style="background: linear-gradient(135deg, #13c2c2 0%, #36cfc9 100%);">
            <t-icon name="user" />
          </div>
        </div>

        <div class="data-card">
          <div class="data-card-content">
            <div class="data-card-title">今日活跃用户</div>
            <div class="data-card-value">{{ formatNumber(todayActiveUsers) }}</div>
            <div class="data-card-trend" :class="{ 'up': dailyActiveRate > 0, 'down': dailyActiveRate < 0 }">
              <t-icon :name="dailyActiveRate >= 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(dailyActiveRate) }}%</span>
              <span class="trend-label">较昨日</span>
            </div>
          </div>
          <div class="data-card-icon" style="background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);">
            <t-icon name="user-circle" />
          </div>
        </div>
      </div>
    </t-card>

    <!-- 订单数据模块 -->
    <t-card title="订单数据" class="dashboard-card">
      <div class="data-cards">
        <div class="data-card">
          <div class="data-card-content">
            <div class="data-card-title">今日订单</div>
            <div class="data-card-value">{{ formatNumber(todayOrders) }}</div>
            <div class="data-card-trend" :class="{ 'up': orderTrend > 0, 'down': orderTrend < 0 }">
              <t-icon :name="orderTrend >= 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(orderTrend) }}%</span>
              <span class="trend-label">较昨日</span>
            </div>
          </div>
          <div class="data-card-icon order-icon">
            <t-icon name="shop" />
          </div>
        </div>

        <div class="data-card">
          <div class="data-card-content">
            <div class="data-card-title">本月订单</div>
            <div class="data-card-value">{{ formatNumber(monthOrders) }}</div>
            <div class="data-card-trend" :class="{ 'up': monthOrderTrend > 0, 'down': monthOrderTrend < 0 }">
              <t-icon :name="monthOrderTrend >= 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(monthOrderTrend) }}%</span>
              <span class="trend-label">较上月</span>
            </div>
          </div>
          <div class="data-card-icon month-order-icon">
            <t-icon name="chart-bubble" />
          </div>
        </div>

        <div class="data-card">
          <div class="data-card-content">
            <div class="data-card-title">平均订单金额</div>
            <div class="data-card-value">¥{{ formatNumber(avgOrderAmount) }}</div>
            <div class="data-card-trend" :class="{ 'up': avgAmountTrend > 0, 'down': avgAmountTrend < 0 }">
              <t-icon :name="avgAmountTrend >= 0 ? 'arrow-up' : 'arrow-down'" />
              <span>{{ Math.abs(avgAmountTrend) }}%</span>
              <span class="trend-label">较上月</span>
            </div>
          </div>
          <div class="data-card-icon amount-icon">
            <t-icon name="money-circle" />
          </div>
        </div>
      </div>

      <!-- 订单趋势图 -->
      <div class="chart-container">
        <div class="chart-header">
          <h3>订单趋势</h3>
          <t-radio-group v-model="orderTimeRange" variant="default-filled" size="small">
            <t-radio-button value="7">最近7天</t-radio-button>
            <t-radio-button value="30">最近30天</t-radio-button>
            <t-radio-button value="90">最近90天</t-radio-button>
          </t-radio-group>
        </div>
        <div class="chart-wrapper">
          <div ref="orderChartRef" class="chart"></div>
          <div v-if="orderLoading" class="chart-loading-overlay">
            <t-loading size="medium" />
          </div>
        </div>
      </div>
    </t-card>

    <!-- 财务数据模块 -->
    <t-card title="财务数据" class="dashboard-card">
      <div class="placeholder">
        <p>财务数据将在后续任务中添加</p>
      </div>
    </t-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
  import {
    Card as TCard,
    RadioGroup as TRadioGroup,
    RadioButton as TRadioButton,
    Loading as TLoading,
    Tooltip as TTooltip,
    Icon as TIcon
  } from 'tdesign-vue-next';
  import * as echarts from 'echarts';

  // 用户增长时间范围选择
  const userGrowthTimeRange = ref('30'); // 默认30天

  // 图表DOM引用
  const userGrowthChartRef = ref<HTMLElement | null>(null);
  let userGrowthChart: echarts.ECharts | null = null;

  // 用户数据相关变量
  const totalUsers = ref(0);
  const monthlyActiveUsers = ref(0);
  const todayActiveUsers = ref(0);
  const yesterdayActiveUsers = ref(0);
  const userGrowthRate = ref(0);
  const monthlyActiveRate = ref(0);
  const dailyActiveRate = ref(0);

  // 用户增长数据接口
  interface UserGrowthData {
    date: string;
    value: number;
  }

  // 生成用户统计数据
  const generateUserStats = () => {
    // 基础数据
    const baseTotal = 10000;
    const baseMonthlyActive = 6000;
    const baseDailyActive = 2000;
    const baseYesterdayActive = 1900;

    // 添加随机波动
    totalUsers.value = Math.floor(baseTotal * (1 + Math.random() * 0.1));
    monthlyActiveUsers.value = Math.floor(baseMonthlyActive * (1 + Math.random() * 0.15));
    todayActiveUsers.value = Math.floor(baseDailyActive * (1 + Math.random() * 0.2));
    yesterdayActiveUsers.value = Math.floor(baseYesterdayActive * (1 + Math.random() * 0.2));

    // 计算增长率
    userGrowthRate.value = Math.floor((Math.random() * 20) - 5); // -5% 到 15% 的增长率
    monthlyActiveRate.value = Math.floor((Math.random() * 25) - 10); // -10% 到 15% 的增长率
    dailyActiveRate.value = Math.floor(((todayActiveUsers.value - yesterdayActiveUsers.value) / yesterdayActiveUsers.value) * 100);
  };

  /**
   * 生成模拟的用户增长数据
   * @param days 需要生成的天数
   * @returns 用户增长数据数组
   */
  const generateUserGrowthData = (days: number): UserGrowthData[] => {
    const data: UserGrowthData[] = [];
    const today = new Date();
    let baseValue = 1000; // 基础用户数

    for (let i = days - 1; i >= 0; i--) {
      const date = new Date();
      date.setDate(today.getDate() - i);

      // 生成随机增长数，模拟用户增长趋势
      // 根据不同时间范围设置不同的增长基数
      const growthBase = days <= 30 ? 50 : (days <= 180 ? 100 : 200);
      const randomGrowth = Math.floor(Math.random() * growthBase) + Math.floor(growthBase * 0.2);
      baseValue += randomGrowth;

      data.push({
        date: `${date.getMonth() + 1}/${date.getDate()}`,
        value: baseValue
      });
    }

    return data;
  };

  // 图表加载状态
  const loading = ref(false);

  // 格式化数字显示（添加千位分隔符）
  const formatNumber = (num: number): string => {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  };


  // 更新图表数据
  const updateUserGrowthChart = async () => {
    if (!userGrowthChart) return;

    loading.value = true;
    userGrowthChart.showLoading({
      text: '加载中...',
      maskColor: 'rgba(255, 255, 255, 0.8)',
      textColor: '#666',
    });

    try {
      const days = parseInt(userGrowthTimeRange.value);
      const data = generateUserGrowthData(days);

      const option: echarts.EChartsOption = {
        tooltip: {
          trigger: 'axis',
          formatter: (params: any) => {
            const dataPoint = params[0];
            return `
            <div style="padding: 3px;">
              <div style="font-size: 14px; color: #333;">
                ${dataPoint.name}
              </div>
              <div style="margin-top: 4px;">
                <span style="display: inline-block; width: 10px; height: 10px; background-color: ${dataPoint.color}; border-radius: 50%; margin-right: 6px;"></span>
                <span>用户总数：${formatNumber(dataPoint.value)}</span>
              </div>
            </div>
          `;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#eee',
          borderWidth: 1,
          padding: [5, 10],
          textStyle: {
            color: '#666',
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.map(item => item.date),
          axisLabel: {
            interval: days > 180 ? 30 : (days > 60 ? 7 : 1), // 根据天数调整x轴标签间隔
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '用户数',
          nameTextStyle: {
            padding: [0, 0, 0, 30], // 调整y轴名称位置
            color: '#666'
          },
          axisLabel: {
            formatter: (value: number) => formatNumber(value),
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#eee',
              type: 'dashed'
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        series: [
          {
            name: '用户总数',
            type: 'line',
            data: data.map(item => item.value),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 3,
              color: '#0052d9'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(0, 82, 217, 0.4)' },
                { offset: 1, color: 'rgba(0, 82, 217, 0.1)' }
              ])
            },
            emphasis: {
              focus: 'series',
              itemStyle: {
                color: '#0052d9',
                borderWidth: 3,
                borderColor: '#fff',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 82, 217, 0.5)'
              }
            },
            markPoint: days <= 30 ? {
              symbol: 'pin',
              symbolSize: 40,
              data: [
                { type: 'max', name: '最大值' }
              ],
              label: {
                formatter: (params: any) => formatNumber(params.value)
              }
            } : undefined
          }
        ]
      };

      userGrowthChart.setOption(option);
      userGrowthChart.hideLoading();
      loading.value = false;
    } catch (error) {
      console.error('更新用户增长图表失败:', error);
      userGrowthChart.hideLoading();
      loading.value = false;
    }
  };

  // 防抖函数
  const debounce = (fn: Function, delay: number) => {
    let timer: number | null = null;
    return function (this: any, ...args: any[]) {
      if (timer) clearTimeout(timer);
      timer = window.setTimeout(() => {
        fn.apply(this, args);
      }, delay);
    };
  };

  // 处理窗口大小变化
  const handleResize = debounce(() => {
    // 重新计算用户增长图表宽度
    if (userGrowthChart && userGrowthChartRef.value) {
      const containerWidth = userGrowthChartRef.value.clientWidth;
      const chartWidth = Math.max(containerWidth - 260, 400);
      userGrowthChart.resize({ width: chartWidth });
    }
    
    // 重新计算订单图表宽度
    if (orderChart && orderChartRef.value) {
      const containerWidth = orderChartRef.value.clientWidth;
      const chartWidth = Math.max(containerWidth - 260, 400);
      orderChart.resize({ width: chartWidth });
    }

    // 300ms后再次重绘，确保容器大小已完全调整
    setTimeout(() => {
      if (userGrowthChart && userGrowthChartRef.value) {
        const containerWidth = userGrowthChartRef.value.clientWidth;
        const chartWidth = Math.max(containerWidth - 260, 400);
        userGrowthChart.resize({ width: chartWidth });
      }
      
      if (orderChart && orderChartRef.value) {
        const containerWidth = orderChartRef.value.clientWidth;
        const chartWidth = Math.max(containerWidth - 260, 400);
        orderChart.resize({ width: chartWidth });
      }
    }, 300);
  }, 200);

  // 监听时间范围变化
  watch(userGrowthTimeRange, () => {
    updateUserGrowthChart();
  });

  // 订单数据相关
  const orderTimeRange = ref('7'); // 默认7天
  const orderChartRef = ref<HTMLElement | null>(null);
  let orderChart: echarts.ECharts | null = null;
  const orderLoading = ref(false);

  // 订单统计数据
  const todayOrders = ref(0);
  const monthOrders = ref(0);
  const avgOrderAmount = ref(0);
  const orderTrend = ref(0);
  const monthOrderTrend = ref(0);
  const avgAmountTrend = ref(0);

  interface OrderData {
    date: string;
    orders: number;
    amount: number;
  }

  // 生成模拟订单数据
  const generateOrderData = (days: number): OrderData[] => {
    const data: OrderData[] = [];
    const today = new Date();
    let baseOrders = 100; // 基础订单数
    let baseAmount = 5000; // 基础订单金额

    for (let i = days - 1; i >= 0; i--) {
      const date = new Date();
      date.setDate(today.getDate() - i);

      // 生成随机波动
      const orderVariation = Math.floor(Math.random() * 30) - 15; // -15 到 15 的随机数
      const amountVariation = Math.random() * 0.2 - 0.1; // -10% 到 10% 的随机波动

      const dailyOrders = Math.max(0, baseOrders + orderVariation);
      const dailyAmount = baseAmount * (1 + amountVariation);

      data.push({
        date: `${date.getMonth() + 1}/${date.getDate()}`,
        orders: dailyOrders,
        amount: dailyAmount
      });

      // 微调基础值，创造趋势
      baseOrders += Math.floor(Math.random() * 3) - 1;
      baseAmount *= (1 + (Math.random() * 0.02 - 0.01));
    }

    return data;
  };

  // 更新订单统计数据
  const updateOrderStats = (data: OrderData[]) => {
    if (data.length === 0) return;

    // 今日订单
    todayOrders.value = data[data.length - 1].orders;

    // 计算昨日订单用于趋势
    const yesterdayOrders = data[data.length - 2]?.orders || todayOrders.value;
    orderTrend.value = Math.round((todayOrders.value - yesterdayOrders) / yesterdayOrders * 100);

    // 本月订单总数
    monthOrders.value = data.slice(-30).reduce((sum, item) => sum + item.orders, 0);

    // 上月订单总数用于趋势
    const lastMonthOrders = data.slice(-60, -30).reduce((sum, item) => sum + item.orders, 0);
    monthOrderTrend.value = Math.round((monthOrders.value - lastMonthOrders) / lastMonthOrders * 100);

    // 平均订单金额
    const totalAmount = data.slice(-30).reduce((sum, item) => sum + item.amount, 0);
    const totalOrders = data.slice(-30).reduce((sum, item) => sum + item.orders, 0);
    avgOrderAmount.value = Math.round(totalAmount / totalOrders);

    // 上月平均订单金额用于趋势
    const lastMonthAmount = data.slice(-60, -30).reduce((sum, item) => sum + item.amount, 0);
    const lastMonthTotalOrders = data.slice(-60, -30).reduce((sum, item) => sum + item.orders, 0);
    const lastMonthAvg = lastMonthAmount / lastMonthTotalOrders;
    avgAmountTrend.value = Math.round((avgOrderAmount.value - lastMonthAvg) / lastMonthAvg * 100);
  };

    // 初始化图表
  const initUserGrowthChart = () => {
    if (!userGrowthChartRef.value) return;

    // 计算实际宽度
    const containerWidth = userGrowthChartRef.value.clientWidth;
    const chartWidth = Math.max(containerWidth - 260, 600); // 最小宽度400px
    userGrowthChart = echarts.init(userGrowthChartRef.value, undefined, {
      width: chartWidth
    });
    updateUserGrowthChart();

    // 确保图表在初始化后正确渲染
    // setTimeout(() => {
    //   userGrowthChart?.resize();
    // }, 0);
  };

  // 初始化订单图表
  const initOrderChart = () => {
    if (!orderChartRef.value) return;

    // 计算实际宽度
    const containerWidth = orderChartRef.value.clientWidth;
    const chartWidth = Math.max(containerWidth - 260, 600); // 最小宽度400px
    console.log('订单图表容器宽度:', chartWidth);
    orderChart = echarts.init(orderChartRef.value, undefined, {
      width: chartWidth 
    });
    updateOrderChart();

    // 确保图表在初始化后正确渲染
    // setTimeout(() => {
    //   if (orderChart && orderChartRef.value) {
    //     const containerWidth = orderChartRef.value.clientWidth;
    //     const chartWidth = Math.max(containerWidth - 250, 400);
    //     orderChart.resize({ width: chartWidth });
    //   }
    // }, 0);
  };

  // 更新订单图表
  const updateOrderChart = async () => {
    if (!orderChart) return;

    orderLoading.value = true;
    orderChart.showLoading({
      text: '加载中...',
      maskColor: 'rgba(255, 255, 255, 0.8)',
      textColor: '#666',
    });

    try {
      const days = parseInt(orderTimeRange.value);
      const data = generateOrderData(days);
      updateOrderStats(data);

      const option: echarts.EChartsOption = {
        tooltip: {
          trigger: 'axis',
          formatter: (params: any) => {
            const dataPoint = params[0];
            return `
            <div style="padding: 3px;">
              <div style="font-size: 14px; color: #333;">
                ${dataPoint.name}
              </div>
              <div style="margin-top: 4px;">
                <span style="display: inline-block; width: 10px; height: 10px; background-color: ${dataPoint.color}; border-radius: 50%; margin-right: 6px;"></span>
                <span>订单数：${formatNumber(dataPoint.value)}</span>
              </div>
            </div>
          `;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#eee',
          borderWidth: 1,
          padding: [5, 10],
          textStyle: {
            color: '#666',
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.map(item => item.date),
          axisLabel: {
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '订单数',
          nameTextStyle: {
            padding: [0, 0, 0, 30],
            color: '#666'
          },
          axisLabel: {
            formatter: (value: number) => formatNumber(value),
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#eee',
              type: 'dashed'
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        series: [
          {
            name: '订单数',
            type: 'line',
            data: data.map(item => item.orders),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 3,
              color: '#0052d9'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(0, 82, 217, 0.4)' },
                { offset: 1, color: 'rgba(0, 82, 217, 0.1)' }
              ])
            },
            emphasis: {
              focus: 'series',
              itemStyle: {
                color: '#0052d9',
                borderWidth: 3,
                borderColor: '#fff',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 82, 217, 0.5)'
              }
            }
          }
        ]
      };

      orderChart.setOption(option);
      orderChart.hideLoading();
      orderLoading.value = false;
    } catch (error) {
      console.error('更新订单图表失败:', error);
      orderChart.hideLoading();
      orderLoading.value = false;
    }
  };

  // 监听订单时间范围变化
  watch(orderTimeRange, () => {
    updateOrderChart();
  });

  // 监听侧边栏折叠状态变化
  const observeSidebarCollapse = (): MutationObserver | null => {
    // 使用MutationObserver监听主内容布局的margin-left变化
    // 这个变化表示侧边栏折叠状态发生了变化
    const mainContent = document.querySelector('.main-content-layout');
    if (!mainContent) return null;

    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
          // 侧边栏状态变化，触发图表重绘
          console.log('侧边栏状态变化，重绘图表');
          handleResize();
        }
      });
    });

    observer.observe(mainContent, { attributes: true, attributeFilter: ['style'] });

    return observer;
  };

  // 生命周期钩子
  onMounted(() => {
    generateUserStats();
    initUserGrowthChart();
    initOrderChart();

    // 添加全局resize事件监听
    window.addEventListener('resize', handleResize);

    // 监听侧边栏折叠状态变化
    const observer = observeSidebarCollapse();

    // 将observer保存到ref中，以便在组件卸载时清理
    if (observer) {
      sidebarObserver.value = observer;
    }
  });

  // 保存MutationObserver实例的ref
  const sidebarObserver = ref<MutationObserver | null>(null);

  onBeforeUnmount(() => {
    // 移除事件监听器
    window.removeEventListener('resize', handleResize);

    // 断开MutationObserver连接
    sidebarObserver.value?.disconnect();
    sidebarObserver.value = null;

    // 释放图表实例
    userGrowthChart?.dispose();
    orderChart?.dispose();
    userGrowthChart = null;
    orderChart = null;
  });
</script>

<style lang="less" scoped>
  .dashboard-container {
    display: flex;
    flex-direction: column;
    // width: calc(100% - 40px);
    gap: 20px;
  }

  .dashboard-card {
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    border-radius: 6px;
  }

  .chart-container {
    margin-bottom: 20px;
  }

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }

  .chart-wrapper {
    position: relative;
    border-radius: 6px;
    background-color: #fff;
    padding: 16px;
    box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.05);
    min-height: 350px;
    display: flex;
    flex-direction: column;
  }

  .chart {
    height: 350px;
    width: 100%;
    flex: 1;
    min-height: 0;
    /* 防止flex子项溢出 */
  }

  .chart-loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 6px;
    z-index: 10;
  }

  .chart-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
    padding: 0 16px;
  }

  .chart-legend {
    display: flex;
    gap: 16px;
  }

  .legend-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666;
  }

  .legend-color {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 2px;
    margin-right: 6px;
  }

  .chart-info {
    color: #999;
    cursor: pointer;

    &:hover {
      color: #0052d9;
    }
  }

  .data-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
    width: 100%;
    // max-width: calc(100% - 40px); /* 使用max-width而不是固定width，给两边留出一些边距 */
  }

  .data-card {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
      transform: translateY(-2px);
    }
  }

  .data-card-content {
    flex: 1;
  }

  .data-card-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
  }

  .data-card-value {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .data-card-trend {
    display: flex;
    align-items: center;
    font-size: 13px;
    gap: 4px;

    &.up {
      color: #2ba471;
    }

    &.down {
      color: #e34d59;
    }

    .trend-label {
      color: #999;
      margin-left: 4px;
    }
  }

  .data-card-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    border-radius: 8px;
    margin-left: 16px;

    .t-icon {
      font-size: 24px;
      color: #fff;
    }
  }

  .order-icon {
    background: linear-gradient(135deg, #0052d9 0%, #1890ff 100%);
  }

  .month-order-icon {
    background: linear-gradient(135deg, #13c2c2 0%, #36cfc9 100%);
  }

  .amount-icon {
    background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
  }

  .placeholder {
    padding: 30px;
    background-color: #f9f9f9;
    border-radius: 6px;
    text-align: center;
    color: #999;
    border: 1px dashed #e0e0e0;
  }
</style>